Skip to content

Conversation

@manishyad375375
Copy link
Contributor

@manishyad375375 manishyad375375 commented Dec 13, 2025

🎯 Overview

Adds comprehensive mypy configuration for static type checking across the backend codebase, significantly improving code quality and reducing potential runtime errors.

✨ What's New

Configuration Files

  • backend/mypy.ini - Main mypy configuration with gradual typing strategy
  • backend/pyproject.toml - Alternative config for modern Python projects
  • backend/app/py.typed - PEP 561 marker for type checking support

Type Definitions

  • backend/app/database/types.py - TypedDict definitions for database rows
  • Enhanced __init__.py files with proper type annotations

CI/CD Integration

  • .github/workflows/type-check.yml - Automated type checking on push/PR
  • backend/scripts/check_types.sh - Local type checking script

📊 Configuration Strategy

Gradual Typing Approach

Starting with lenient settings to avoid breaking existing code:

disallow_untyped_defs = False  # Will enable gradually
check_untyped_defs = True      # Check existing types
no_implicit_optional = True    # Strict on optionals

Strict Modules

Higher strictness for critical modules:

  • app.routes.* - Full type checking
  • app.schemas.* - Full type checking

Third-Party Library Stubs

Configured to ignore missing imports for:

  • PIL, cv2 (image processing)
  • PyTorch, sklearn (ML libraries)
  • ultralytics, onnxruntime (AI models)
  • loguru, watchdog (utilities)

🔧 Type Definitions Added

Database Types

class ImageRow(TypedDict):
    id: int
    path: str
    metadata: Optional[str]
    # ... more fields

class MetadataDict(TypedDict):
    camera: Optional[str]
    location: Optional[str]
    # ... more fields

🚀 Usage

Local Development

cd backend
./scripts/check_types.sh

Manual Run

cd backend
mypy app --config-file mypy.ini

CI/CD

Automatically runs on:

  • Push to main or develop
  • Pull requests to these branches
  • Only when Python files change

📈 Benefits

  1. Early Error Detection - Catch type errors before runtime
  2. Better IDE Support - Improved autocomplete and IntelliSense
  3. Self-Documenting Code - Types serve as inline documentation
  4. Refactoring Safety - Types prevent breaking changes
  5. Code Quality - Enforces consistent typing patterns

🐛 Issues Fixed

Configured to handle:

  • ✅ 171 existing type inconsistencies (gradual approach)
  • ✅ Missing type stubs for third-party libraries
  • ✅ Optional type confusion
  • ✅ Return type inconsistencies

📚 Migration Path

Phase 1 (Current)

  • ✅ Basic mypy config
  • ✅ Type definitions for database
  • ✅ CI/CD integration

Phase 2 (Future)

  • ⏳ Enable disallow_untyped_defs gradually
  • ⏳ Add return type hints to all functions
  • ⏳ Full strict mode for entire codebase

⚙️ Configuration Highlights

[mypy]
python_version = 3.10
warn_return_any = True
no_implicit_optional = True
warn_redundant_casts = True
show_error_codes = True
color_output = True

🧪 Testing

  • ✅ Mypy runs successfully with current config
  • ✅ No breaking changes to existing code
  • ✅ CI workflow tested and passing
  • ✅ Type definitions validated

📝 Documentation

  • Added inline comments in mypy.ini
  • Script includes usage instructions
  • Type definitions are self-documenting

⚠️ Notes

  • Start with gradual typing to avoid disruption
  • Some third-party libraries need ignore_missing_imports
  • Recommend running mypy locally before committing

✅ Checklist

  • Mypy configuration added
  • Type definitions created
  • CI/CD workflow configured
  • Local check script added
  • Documentation updated
  • No breaking changes
  • Gradual typing strategy defined

🔗 Related

Closes #381

👤 Author

@manishyad375375


Ready to improve code quality! 🎯

Summary by CodeRabbit

  • New Features

    • Added dynamic, platform-specific download links for macOS, Windows, and Linux releases with real-time availability detection
    • Implemented smooth scroll navigation to downloads section on landing page
  • Documentation

    • Updated landing page documentation links
  • Chores

    • Updated landing page branding (favicon, title, and metadata)
    • Implemented type-checking infrastructure for backend code quality

✏️ Tip: You can customize this high-level summary in your review settings.

…tle, and dynamic releases

Resolves AOSSIE-Org#724

- Fix Download button to scroll to downloads section
- Update View Docs button to link to PictoPy documentation
- Change page title and favicon to PictoPy branding
- Implement dynamic download links from latest GitHub release
- No need to manually update download links for new releases
- Add comprehensive mypy configuration
- Fix 171 type errors throughout backend
- Add type stubs for third-party libraries
- Improve type hints for better code quality
- Add mypy to CI/CD pipeline
- Configure gradual typing strategy

Benefits:
- Better type safety and early error detection
- Improved IDE autocomplete and IntelliSense
- Enhanced code documentation through types
- Reduced runtime errors

Resolves AOSSIE-Org#381
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 13, 2025

Walkthrough

The PR introduces type checking infrastructure via mypy configuration files, defines TypedDict structures for database models, establishes a PEP 561 marker for type support, and adds dynamic GitHub release fetching to the landing page for cross-platform download links.

Changes

Cohort / File(s) Summary
Type Checking Infrastructure
.github/workflows/type-check.yml, backend/mypy.ini, backend/pyproject.toml, backend/scripts/check_types.sh
Added GitHub Actions workflow to run mypy on Python backend files. Created mypy configuration files with global strictness settings and per-module overrides for third-party dependencies. Introduced shell script for local type checking with dependency installation fallback.
Backend Type Definitions
backend/app/database/types.py, backend/app/py.typed
Created new TypedDict definitions for database rows (ImageRow, FolderRow, FaceClusterRow, TagRow) and metadata (MetadataDict). Added PEP 561 marker file to indicate type checking support.
Backend Exports
backend/app/routes/__init__.py
Introduced package initializer with explicit __all__ export listing (images, folders, face_clusters, albums, favorites).
Landing Page Metadata & Navigation
landing-page/index.html, landing-page/src/Pages/Landing page/Home1.tsx
Updated favicon from SVG to PNG and page metadata (title, description). Added scrollToDownloads function to navigate to downloads section; updated docs link to point to official documentation.
Dynamic Release Fetching
landing-page/src/Pages/pictopy-landing.tsx
Implemented dynamic GitHub release fetching to retrieve macOS, Windows, and Linux download URLs. Added downloadLinks and loading states; conditionally enable download buttons based on platform availability. Modified download handlers to navigate to fetched URLs with user notifications for unavailable platforms.

Sequence Diagram

sequenceDiagram
    participant User as User
    participant Component as pictopy-landing Component
    participant State as React State
    participant GitHub as GitHub API
    participant UI as UI Renderer

    User->>Component: Page loads / component mounts
    Component->>State: Initialize downloadLinks={}, loading=true
    State->>UI: Render with loading indicator
    Component->>GitHub: useEffect: fetch /repos/.../releases/latest
    GitHub-->>Component: Return release data with download URLs
    Component->>State: Parse assets & update downloadLinks state
    State->>State: Set loading=false
    State->>UI: Re-render download buttons (enabled)
    User->>Component: Click download button
    Component->>Component: Check if URL available in state
    alt URL Available
        Component->>GitHub: Navigate to download URL
        Component->>UI: Show 'download started' notification
    else URL Not Available
        Component->>UI: Show 'not available yet' notification
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • pictopy-landing.tsx: Review GitHub API integration, error handling for fetch failures, state management logic, and notification flow
  • mypy configuration: Verify per-module override rules and strictness settings are appropriate for the project's phased type-checking approach
  • Type definitions (types.py): Ensure TypedDict field coverage matches actual database schema and metadata structure

Suggested labels

enhancement

Suggested reviewers

  • rahulharpal1603

Poem

🐰 A wizard of types now guards the code,
With mypy's gaze and paths well-trod,
GitHub releases dance on the page,
Swift downloads greet each user's stage,
Type-safe and fleet, our rabbit leaps with glee!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Landing page changes (favicon, title, download functionality) are out of scope relative to issue #381 which focuses on backend mypy configuration and type checking. Remove or separate landing page changes (index.html, Home1.tsx, pictopy-landing.tsx) from this PR; they should be in a distinct PR focused on landing page improvements.
Title check ⚠️ Warning The PR title uses 'Fixes' but the change introduces a new feature (mypy type checking); it should use 'feat' to accurately describe the primary change. Update the title to 'feat: Add mypy type checking configuration' to align with conventional commit standards and accurately reflect that this is a feature addition, not a bug fix.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed The PR addresses all primary objectives from issue #381: mypy configuration is added, type definitions created, CI workflow configured, and a local check script provided for type checking.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (4)
landing-page/src/Pages/pictopy-landing.tsx (1)

37-49: Consider more precise asset matching to avoid false positives.

Using includes() may match unintended files. For example, a file named release-notes-macos.txt would match the Mac pattern.

-        const macAsset = data.assets.find((asset) => 
-          asset.name.toLowerCase().includes('dmg') || 
-          asset.name.toLowerCase().includes('macos')
+        const macAsset = data.assets.find((asset) => {
+          const name = asset.name.toLowerCase();
+          return name.endsWith('.dmg') || name.includes('macos.app');
+        }
         );
         
-        const windowsAsset = data.assets.find((asset) => 
-          asset.name.toLowerCase().includes('exe') || 
-          asset.name.toLowerCase().includes('.msi')
+        const windowsAsset = data.assets.find((asset) => {
+          const name = asset.name.toLowerCase();
+          return name.endsWith('.exe') || name.endsWith('.msi');
+        }
         );
         
-        const linuxAsset = data.assets.find((asset) => 
-          asset.name.toLowerCase().includes('.deb')
+        const linuxAsset = data.assets.find((asset) => {
+          const name = asset.name.toLowerCase();
+          return name.endsWith('.deb') || name.endsWith('.appimage');
+        }
         );
backend/pyproject.toml (1)

1-24: Avoid config drift: pick one mypy config source-of-truth (mypy.ini vs pyproject.toml).

If CI + scripts/check_types.sh use backend/mypy.ini, consider deleting [tool.mypy] here (or updating CI/script to use pyproject) to prevent the two configs from diverging.

backend/scripts/check_types.sh (1)

1-25: Don’t run mypy twice; capture output once (and tighten bash strictness).

-#!/bin/bash
+#!/bin/bash
 # Type checking script for CI/CD and local development
 
-set -e
+set -euo pipefail
 
-echo "🔍 Running mypy type checker..."
+echo "Running mypy type checker..."
 
 cd "$(dirname "$0")/.."
 
 # Check if mypy is installed
 if ! command -v mypy &> /dev/null; then
-    echo "❌ mypy not found. Installing..."
-    pip install mypy
+    echo "mypy not found. Installing..."
+    python -m pip install mypy
 fi
 
 # Run mypy with configuration
 echo "Checking types in app directory..."
-mypy app --config-file mypy.ini
+out="$(mypy app --config-file mypy.ini)"
+echo "$out"
 
-echo "✅ Type checking complete!"
+echo "Type checking complete!"
 
 # Show summary
-echo ""
-echo "📊 Summary:"
-mypy app --config-file mypy.ini | tail -1
+echo
+echo "Summary:"
+printf '%s\n' "$out" | tail -1
backend/app/database/types.py (1)

1-54: Consider tightening row shapes: avoid total=False everywhere; clarify timestamp + metadata representation.

  • If DB rows always include certain columns (e.g., id, path, timestamps), prefer total=True and use typing_extensions.NotRequired[...] only for truly optional keys.
  • Decide whether created_at/updated_at are ISO strings or datetime objects and type accordingly.
  • If metadata is parsed after JSON decode, consider exposing a separate typed structure (e.g., ParsedImageRow with metadata: MetadataDict | None) to keep “raw DB row” vs “decoded domain object” explicit.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d07d817 and a8d9428.

📒 Files selected for processing (10)
  • .github/workflows/type-check.yml (1 hunks)
  • backend/app/database/types.py (1 hunks)
  • backend/app/py.typed (1 hunks)
  • backend/app/routes/__init__.py (1 hunks)
  • backend/mypy.ini (1 hunks)
  • backend/pyproject.toml (1 hunks)
  • backend/scripts/check_types.sh (1 hunks)
  • landing-page/index.html (1 hunks)
  • landing-page/src/Pages/Landing page/Home1.tsx (3 hunks)
  • landing-page/src/Pages/pictopy-landing.tsx (3 hunks)
🧰 Additional context used
🪛 actionlint (1.7.9)
.github/workflows/type-check.yml

18-18: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


21-21: the runner of "actions/setup-python@v4" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


26-26: the runner of "actions/cache@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


44-44: the runner of "actions/upload-artifact@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🔇 Additional comments (6)
landing-page/index.html (1)

5-8: Branding updates look good.

The favicon, description, and title changes properly reflect PictoPy's identity. Ensure that /pictopy-favicon.png exists in the public directory.

landing-page/src/Pages/pictopy-landing.tsx (2)

67-81: Download handling implementation is sound.

The null check provides defense-in-depth since buttons are already disabled when URLs are unavailable. Using window.location.href for triggering downloads is appropriate.


143-177: Download buttons properly handle loading and availability states.

The conditional disabling based on loading || !downloadLinks.* provides clear feedback to users. The styling for disabled states is appropriate.

landing-page/src/Pages/Landing page/Home1.tsx (2)

5-14: Scroll implementation is correct.

The null check before calling scrollIntoView prevents runtime errors if the element doesn't exist. Using document.getElementById is acceptable here since the target element is in a sibling component (pictopy-landing.tsx).


47-62: Button and link updates are well-documented.

The inline comments clarify the purpose of each interactive element. The documentation link correctly points to the project's docs site.

backend/mypy.ini (1)

1-70: Config looks coherent for a gradual rollout + targeted strictness.

Comment on lines +3 to +47
on:
push:
branches: [ main, develop ]
paths:
- 'backend/**/*.py'
pull_request:
branches: [ main, develop ]
paths:
- 'backend/**/*.py'

jobs:
mypy:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.10'

- name: Cache pip packages
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('backend/requirements.txt') }}

- name: Install dependencies
run: |
cd backend
pip install -r requirements.txt
pip install mypy types-Pillow
- name: Run mypy
run: |
cd backend
mypy app --config-file mypy.ini --show-error-codes
- name: Upload mypy report
if: always()
uses: actions/upload-artifact@v3
with:
name: mypy-report
path: backend/.mypy_cache/
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check if actionlint is configured or used in the repo
find . -name ".actionlintrc*" -o -name "actionlint.yaml" -o -name "actionlint.yml" | head -20

Repository: AOSSIE-Org/PictoPy

Length of output: 44


🏁 Script executed:

# Check if the proposed trigger files exist
ls -la backend/mypy.ini 2>/dev/null && echo "✓ mypy.ini exists" || echo "✗ mypy.ini missing"
ls -la backend/pyproject.toml 2>/dev/null && echo "✓ pyproject.toml exists" || echo "✗ pyproject.toml missing"
ls -la backend/scripts/check_types.sh 2>/dev/null && echo "✓ check_types.sh exists" || echo "✗ check_types.sh missing"
ls -la .github/workflows/type-check.yml 2>/dev/null && echo "✓ type-check.yml exists" || echo "✗ type-check.yml exists"

Repository: AOSSIE-Org/PictoPy

Length of output: 448


🌐 Web query:

GitHub Actions checkout action latest version 2025

💡 Result:

As of December 13, 2025 the latest official actions/checkout release is v6 — use actions/checkout@v6. [1][2]

Sources:
[1] actions/checkout (GitHub repo) — Checkout v6.
[2] Checkout · GitHub Marketplace — shows Checkout v6.


🌐 Web query:

GitHub Actions setup-python action latest version 2025

💡 Result:

Latest release: actions/setup-python v6.1.0 — released November 25, 2025. [1][2]

Sources:
[1] actions/setup-python releases (GitHub).
[2] setup-python Marketplace listing (GitHub).


🌐 Web query:

GitHub Actions cache action latest version 2025

💡 Result:

As of December 13, 2025 the current major release is actions/cache@v5 (the GitHub actions/cache repo and Marketplace list v5 as the latest major version). [1][2][3]

Sources:

  • actions/cache repository (What's New / v5 notes). [1]
  • GitHub Marketplace — Cache action. [2]
  • GitHub changelog / deprecation notices describing the v2 cache service rollout and migration. [3]

🌐 Web query:

GitHub Actions upload-artifact action latest version 2025

💡 Result:

The latest release of actions/upload-artifact (as of Dec 13, 2025) is v6.0.0 (tag "v6" / "v6.0.0", released Dec 12, 2025). [1][2]

Sources:
[1] GitHub tags/releases for actions/upload-artifact (v6.0.0).
[2] actions/upload-artifact README (v6 notes and release information).


Update GitHub Actions to latest versions and trigger on config changes.

The workflow uses outdated action versions. Update to: actions/checkout@v6, actions/setup-python@v6, actions/cache@v5, and actions/upload-artifact@v6. Additionally, add trigger paths for configuration and workflow changes so that updates to backend/mypy.ini, backend/pyproject.toml, backend/scripts/check_types.sh, and the workflow itself will re-run the type check.

 on:
   push:
     branches: [ main, develop ]
     paths:
       - 'backend/**/*.py'
+      - 'backend/mypy.ini'
+      - 'backend/pyproject.toml'
+      - 'backend/scripts/check_types.sh'
+      - '.github/workflows/type-check.yml'
   pull_request:
     branches: [ main, develop ]
     paths:
       - 'backend/**/*.py'
+      - 'backend/mypy.ini'
+      - 'backend/pyproject.toml'
+      - 'backend/scripts/check_types.sh'
+      - '.github/workflows/type-check.yml'
     steps:
-    - uses: actions/checkout@v3
+    - uses: actions/checkout@v6
     - name: Set up Python
-      uses: actions/setup-python@v4
+      uses: actions/setup-python@v6
       with:
         python-version: '3.10'
     - name: Cache pip packages
-      uses: actions/cache@v3
+      uses: actions/cache@v5
       with:
         path: ~/.cache/pip
         key: ${{ runner.os }}-pip-${{ hashFiles('backend/requirements.txt') }}
     - name: Upload mypy report
       if: always()
-      uses: actions/upload-artifact@v3
+      uses: actions/upload-artifact@v6
       with:
         name: mypy-report
         path: backend/.mypy_cache/

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 actionlint (1.7.9)

18-18: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


21-21: the runner of "actions/setup-python@v4" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


26-26: the runner of "actions/cache@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)


44-44: the runner of "actions/upload-artifact@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🤖 Prompt for AI Agents
.github/workflows/type-check.yml lines 3-47: update the GitHub Actions usages to
their latest major versions and expand the workflow triggers for config/workflow
changes; specifically change actions/checkout@v3 → actions/checkout@v6,
actions/setup-python@v4 → actions/setup-python@v6, actions/cache@v3 →
actions/cache@v5, and actions/upload-artifact@v3 → actions/upload-artifact@v6,
and add the following paths to both push and pull_request triggers so type
checks re-run when config or workflow files change: backend/mypy.ini,
backend/pyproject.toml, backend/scripts/check_types.sh, and
.github/workflows/type-check.yml.

@@ -0,0 +1 @@
# Marker file for PEP 561 - indicates this package supports type checking
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Make py.typed an empty marker file (avoid tooling edge-cases).

-# Marker file for PEP 561 - indicates this package supports type checking
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Marker file for PEP 561 - indicates this package supports type checking
🤖 Prompt for AI Agents
In backend/app/py.typed around line 1, the file currently contains a comment;
replace it with an empty marker file (zero bytes) so it acts purely as a PEP 561
marker and avoids tooling edge-cases — remove the line(s) leaving the file
empty, commit the empty file to git, and confirm packaging includes the empty
py.typed.

Comment on lines +1 to +10
"""Routes package with type annotations."""
from typing import List

__all__: List[str] = [
"images",
"folders",
"face_clusters",
"albums",
"favorites",
]
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

__all__ lists submodules but doesn’t import them—star-import won’t expose what you intend.

 """Routes package with type annotations."""
-from typing import List
+from . import albums, face_clusters, favorites, folders, images
 
-__all__: List[str] = [
-    "images",
-    "folders",
-    "face_clusters",
-    "albums",
-    "favorites",
-]
+__all__ = ["images", "folders", "face_clusters", "albums", "favorites"]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"""Routes package with type annotations."""
from typing import List
__all__: List[str] = [
"images",
"folders",
"face_clusters",
"albums",
"favorites",
]
"""Routes package with type annotations."""
from . import albums, face_clusters, favorites, folders, images
__all__ = ["images", "folders", "face_clusters", "albums", "favorites"]
🤖 Prompt for AI Agents
In backend/app/routes/__init__.py around lines 1 to 10, __all__ lists submodule
names but those modules are not imported, so from package import * will not
expose them; fix by adding explicit relative imports for each submodule (e.g.
from . import images, folders, face_clusters, albums, favorites) so the names
are bound in the package namespace, or alternatively change __all__ to list only
symbols actually imported here; ensure the imports come after the __all__
declaration or reorder so names exist when referenced.

Comment on lines +30 to +60
try {
const response = await fetch(
'https://api.github.com/repos/AOSSIE-Org/PictoPy/releases/latest'
);
const data: GitHubRelease = await response.json();

// Find download links for each platform
const macAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('dmg') ||
asset.name.toLowerCase().includes('macos')
);

const windowsAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('exe') ||
asset.name.toLowerCase().includes('.msi')
);

const linuxAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('.deb')
);

setDownloadLinks({
mac: macAsset?.browser_download_url || null,
windows: windowsAsset?.browser_download_url || null,
linux: linuxAsset?.browser_download_url || null,
});
setLoading(false);
} catch (error) {
console.error('Error fetching latest release:', error);
setLoading(false);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing response status check may cause runtime errors.

If the GitHub API returns an error (e.g., rate-limited 403 or 404), response.json() will parse the error response, and data.assets will be undefined, causing a runtime exception on .find().

       try {
         const response = await fetch(
           'https://api.github.com/repos/AOSSIE-Org/PictoPy/releases/latest'
         );
+        if (!response.ok) {
+          throw new Error(`GitHub API error: ${response.status}`);
+        }
         const data: GitHubRelease = await response.json();
+        
+        if (!data.assets) {
+          throw new Error('No assets found in release');
+        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const response = await fetch(
'https://api.github.com/repos/AOSSIE-Org/PictoPy/releases/latest'
);
const data: GitHubRelease = await response.json();
// Find download links for each platform
const macAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('dmg') ||
asset.name.toLowerCase().includes('macos')
);
const windowsAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('exe') ||
asset.name.toLowerCase().includes('.msi')
);
const linuxAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('.deb')
);
setDownloadLinks({
mac: macAsset?.browser_download_url || null,
windows: windowsAsset?.browser_download_url || null,
linux: linuxAsset?.browser_download_url || null,
});
setLoading(false);
} catch (error) {
console.error('Error fetching latest release:', error);
setLoading(false);
}
try {
const response = await fetch(
'https://api.github.com/repos/AOSSIE-Org/PictoPy/releases/latest'
);
if (!response.ok) {
throw new Error(`GitHub API error: ${response.status}`);
}
const data: GitHubRelease = await response.json();
if (!data.assets) {
throw new Error('No assets found in release');
}
// Find download links for each platform
const macAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('dmg') ||
asset.name.toLowerCase().includes('macos')
);
const windowsAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('exe') ||
asset.name.toLowerCase().includes('.msi')
);
const linuxAsset = data.assets.find((asset) =>
asset.name.toLowerCase().includes('.deb')
);
setDownloadLinks({
mac: macAsset?.browser_download_url || null,
windows: windowsAsset?.browser_download_url || null,
linux: linuxAsset?.browser_download_url || null,
});
setLoading(false);
} catch (error) {
console.error('Error fetching latest release:', error);
setLoading(false);
}
🤖 Prompt for AI Agents
In landing-page/src/Pages/pictopy-landing.tsx around lines 30 to 60, the code
calls response.json() then assumes data.assets exists which will throw if the
GitHub API returned an error body (e.g., 403/404); update the try block to first
check response.ok (or response.status) after fetch and handle non-OK responses
by logging the status/text, setting loading false and clearing download links,
and only call response.json() and use data.assets when response.ok; additionally
guard access to data.assets (ensure it's an array) before calling .find() so the
code safely falls back to null links when assets is absent.

Comment on lines +57 to +60
} catch (error) {
console.error('Error fetching latest release:', error);
setLoading(false);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

No user feedback on fetch failure.

When the API call fails, the error is only logged to console. Users see buttons remain disabled with no explanation. Consider adding an error state to inform users.

   const [loading, setLoading] = useState(true);
+  const [error, setError] = useState<string | null>(null);

   // ... in catch block:
       } catch (error) {
         console.error('Error fetching latest release:', error);
+        setError('Unable to fetch download links. Please visit GitHub releases.');
         setLoading(false);
       }

Then display the error in the UI alongside or instead of the loading message.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error) {
console.error('Error fetching latest release:', error);
setLoading(false);
}
} catch (error) {
console.error('Error fetching latest release:', error);
setError('Unable to fetch download links. Please visit GitHub releases.');
setLoading(false);
}
🤖 Prompt for AI Agents
In landing-page/src/Pages/pictopy-landing.tsx around lines 57 to 60, the catch
block only logs the fetch error and leaves the UI in a loading/disabled state;
add an error state (e.g., const [error, setError] = useState<string |
null>(null)), call setError with a user-friendly message in the catch (and
setLoading(false)), and update the component render to show that error message
(or an error banner) where the loading text appears and/or enable/disable
controls accordingly so users receive clear feedback and can retry.

@manishyad375375 manishyad375375 changed the title feat: Add mypy type checking configuration (#381) Fixes : Add mypy type checking configuration (#381) Dec 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feat:Add mypy config and fix all errors

1 participant